package com.example.data.factory.common.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParamParser {
    private static final ObjectMapper objectMapper = new ObjectMapper ();

    /**
     * 解析输入参数（支持单个对象和数组）
     */
    public static Map<String, String> parseInputParams(String inputParam) throws IOException {
        if (inputParam == null || inputParam.isEmpty ()) {
            return Map.of ();
        }

        // 尝试解析为单个对象
        try {
            Map<String, String> singleParam = objectMapper.readValue ( inputParam, new TypeReference<Map<String, String>> () {
            } );
            return extractSingleParam ( singleParam );
        } catch (Exception e) {
            // 如果不是单个对象，则尝试解析为数组
        }

        // 尝试解析为数组
        try {
            List<Map<String, String>> paramList = objectMapper.readValue ( inputParam, new TypeReference<List<Map<String, String>>> () {
            } );
            return extractArrayParams ( paramList );
        } catch (Exception e) {
            throw new IOException ( "无法解析输入参数: " + e.getMessage (), e );
        }
    }

    /**
     * 提取单个参数对象
     */
    private static Map<String, String> extractSingleParam(Map<String, String> param) {
        Map<String, String> paramMap = new HashMap<> ();
        String paramName = param.get ( "paramId" );
        String paramDefault = param.get ( "paramDefault" );

        if (paramName != null && paramDefault != null) {
            paramMap.put ( paramName, paramDefault );
        }

        return paramMap;
    }

    /**
     * 提取参数数组
     */
    private static Map<String, String> extractArrayParams(List<Map<String, String>> paramList) {
        Map<String, String> paramMap = new HashMap<> ();
        for (Map<String, String> param : paramList) {
            String paramName = param.get ( "paramName" );
            String paramDefault = param.get ( "paramDefault" );

            if (paramName != null && paramDefault != null) {
                paramMap.put ( paramName, paramDefault );
            }
        }

        return paramMap;
    }
}
